import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Avatar, Dropdown, Space, Button, Input, Badge, Drawer } from 'antd';
import {
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
  SearchOutlined,
  BellOutlined,
  DownOutlined,
  KeyOutlined,
  MenuOutlined,
  DashboardOutlined,
  CloudOutlined,
  DatabaseOutlined,
  ContainerOutlined,
  GlobalOutlined,
  SecurityScanOutlined,
  CodeOutlined,
  RobotOutlined,
  ToolOutlined,
  ApiOutlined,
} from '@ant-design/icons';
import { useAuthStore } from '../store/auth';

const TopNavigation: React.FC = () => {
  const { user, logout } = useAuthStore();
  const navigate = useNavigate();
  const location = useLocation();
  const [drawerVisible, setDrawerVisible] = useState(false);

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  // 判断是否在主控制台页面
  const isDashboard = location.pathname === '/app/dashboard' || 
                     location.pathname === '/app' || 
                     location.pathname === '/app/';

  // 抽屉菜单数据
  const menuSections = [
    {
      title: '计算',
      icon: <DatabaseOutlined style={{ color: '#1890ff' }} />,
      items: [
        { title: '弹性计算', subItems: ['资源管理', '运维中心'] },
      ]
    },
    {
      title: '安全',
      icon: <SecurityScanOutlined style={{ color: '#52c41a' }} />,
      items: [
        { title: '云安全', subItems: ['堡垒机'] },
        { title: '数据安全', subItems: ['密钥管理系统'] },
      ]
    },
    {
      title: '容器与中间件',
      icon: <ContainerOutlined style={{ color: '#722ed1' }} />,
      items: [
        { title: '容器服务', subItems: ['分布式消息服务'] },
        { title: '云原生可观测', subItems: ['监控中心'] },
      ]
    },
    {
      title: '计算管理',
      icon: <ToolOutlined style={{ color: '#13c2c2' }} />,
      items: [
        { title: '安全', subItems: [] },
        { title: '容器与中间件', subItems: [] },
        { title: '人工智能与算法', subItems: [] },
      ]
    },
    {
      title: '人工智能与算法',
      icon: <RobotOutlined style={{ color: '#fa8c16' }} />,
      items: [
        { title: '机器学习', subItems: ['容器集群'] },
      ]
    },
    {
      title: 'API开放中心',
      icon: <ApiOutlined style={{ color: '#eb2f96' }} />,
      items: [
        { title: 'AI应用平台', subItems: [] },
      ]
    },
  ];

  // 用户下拉菜单
  const userMenuItems = [
    {
      key: 'user-info',
      label: (
        <div style={{ padding: '8px 0', borderBottom: '1px solid #f0f0f0', marginBottom: '8px' }}>
          <div style={{ fontSize: '14px', fontWeight: 'bold', display: 'block' }}>
            {user?.full_name || user?.username}
          </div>
          <div style={{ fontSize: '12px', color: '#999', marginBottom: '2px' }}>
            {user?.email}
          </div>
          <div style={{ fontSize: '11px', color: '#bbb' }}>
            账号ID: {user?.user_id}
          </div>
        </div>
      ),
      disabled: true,
    },
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '账户设置',
    },
    {
      key: 'aksk',
      icon: <KeyOutlined />,
      label: 'API密钥管理',
    },
    {
      type: 'divider' as const,
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout,
    },
  ];

  const handleUserMenuClick = ({ key }: { key: string }) => {
    if (key === 'profile') {
      navigate('/app/account/profile');
    } else if (key === 'settings') {
      navigate('/app/account/profile');
    } else if (key === 'aksk') {
      navigate('/app/account/aksk');
    }
  };

  const handleMenuItemClick = (path: string) => {
    navigate(path);
    setDrawerVisible(false);
  };

  return (
    <>
      <div style={{ 
        padding: '0 24px', 
        background: '#fff',
        borderBottom: '1px solid #e8e8e8',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: 50,
        width: '100%',
        boxShadow: '0 1px 4px rgba(0,21,41,.08)'
      }}>
        {/* 左侧：菜单按钮、Logo、总览按钮和搜索框 */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          {/* 菜单按钮 */}
          <Button
            type="text"
            icon={<MenuOutlined />}
            onClick={() => setDrawerVisible(true)}
            style={{
              width: 32,
              height: 32,
              borderRadius: '6px',
              color: '#595959'
            }}
          />

          {/* Logo区域 */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <img 
              src="/logo.png" 
              alt="星链saas运维系统" 
              style={{ 
                width: 32, 
                height: 32, 
                borderRadius: '6px',
                objectFit: 'contain'
              }} 
            />
            <span style={{ fontSize: '16px', color: '#262626', fontWeight: 600 }}>
              星链saas运维系统
            </span>
          </div>

          {/* 总览按钮 */}
          <Button
            type="text"
            icon={<DashboardOutlined />}
            onClick={() => navigate('/app/dashboard')}
            style={{ 
              fontSize: '12px',
              height: '28px',
              padding: '0 12px',
              borderRadius: '4px',
              display: 'flex',
              alignItems: 'center',
              gap: '4px',
              fontWeight: 400,
              color: isDashboard ? '#1890ff' : '#595959',
              backgroundColor: 'transparent',
              border: 'none'
            }}
          >
            总览
          </Button>
          
          {/* 搜索框 */}
          <Input
            placeholder="搜索产品或者文档"
            prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
            style={{
              width: '320px',
              borderRadius: '6px',
              backgroundColor: '#f5f5f5',
              border: 'none',
              fontSize: '14px'
            }}
            size="middle"
          />
        </div>

        {/* 右侧：工具栏和用户信息 */}
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: '12px'
        }}>
          {/* 工具按钮组 */}
          <Space size="small">
            <Button
              type="text"
              icon={<DownOutlined style={{ fontSize: '10px' }} />}
              iconPosition="end"
              style={{ 
                fontSize: '14px',
                height: '32px',
                padding: '0 12px',
                color: '#595959',
                border: 'none'
              }}
            >
              工具
            </Button>
            
            <Button
              type="text"
              icon={<DownOutlined style={{ fontSize: '10px' }} />}
              iconPosition="end"
              style={{ 
                fontSize: '14px',
                height: '32px',
                padding: '0 12px',
                color: '#595959',
                border: 'none'
              }}
            >
              费用
            </Button>
            
            <Button
              type="text"
              icon={<DownOutlined style={{ fontSize: '10px' }} />}
              iconPosition="end"
              style={{ 
                fontSize: '14px',
                height: '32px',
                padding: '0 12px',
                color: '#595959',
                border: 'none'
              }}
            >
              支持
            </Button>
            
            <Button
              type="text"
              style={{ 
                fontSize: '14px',
                height: '32px',
                padding: '0 12px',
                color: '#595959',
                border: 'none'
              }}
            >
              文档
            </Button>
          </Space>

          {/* 分隔符 */}
          <div style={{ height: '16px', width: '1px', background: '#d9d9d9' }} />

          {/* 通知图标 */}
          <Badge dot>
            <Button
              type="text"
              icon={<BellOutlined />}
              style={{
                width: 32,
                height: 32,
                borderRadius: '6px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#595959',
                border: 'none'
              }}
            />
          </Badge>

          {/* 用户头像和系统管理员下拉 */}
          <Dropdown
            menu={{ 
              items: userMenuItems,
              onClick: handleUserMenuClick
            }}
            placement="bottomRight"
            trigger={['click']}
          >
            <div style={{ 
              display: 'flex', 
              alignItems: 'center',
              cursor: 'pointer',
              padding: '4px 8px',
              borderRadius: '6px',
              transition: 'background-color 0.2s',
              gap: '8px',
              backgroundColor: 'transparent'
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = 'transparent';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = 'transparent';
            }}
            >
              <Avatar 
                size={28}
                style={{ 
                  backgroundColor: '#1890ff',
                  cursor: 'pointer'
                }}
              >
                A
              </Avatar>
              <span style={{ 
                fontSize: '14px', 
                color: '#262626',
                fontWeight: 500
              }}>
                系统管理员
              </span>
              <DownOutlined style={{ fontSize: '10px', color: '#999' }} />
            </div>
          </Dropdown>
        </div>
      </div>

      {/* 侧边抽屉菜单 */}
      <Drawer
        title={
          <div style={{ 
            display: 'flex', 
            alignItems: 'center', 
            gap: '12px',
            padding: '8px 0'
          }}>
            <Input
              placeholder="搜索产品或者文档"
              prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
              style={{
                borderRadius: '6px',
                backgroundColor: '#f5f5f5',
                border: 'none',
                flex: 1
              }}
            />
            <span style={{ 
              fontSize: '14px', 
              color: '#1890ff',
              cursor: 'pointer',
              whiteSpace: 'nowrap'
            }}>
              最近访问：
            </span>
            <Button 
              type="link" 
              style={{ 
                fontSize: '14px', 
                padding: 0,
                height: 'auto'
              }}
              onClick={() => handleMenuItemClick('/app/containers')}
            >
              资源管理
            </Button>
          </div>
        }
        placement="left"
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        width={800}
        bodyStyle={{ 
          padding: 0,
          background: '#fafafa'
        }}
        headerStyle={{ 
          borderBottom: '1px solid #e8e8e8',
          background: '#fff'
        }}
      >
        <div style={{ background: '#fff', minHeight: '100%', padding: '24px 40px' }}>
          {/* 3列网格布局 - 每行3个分类 */}
          <div style={{ 
            display: 'grid', 
            gridTemplateColumns: 'repeat(3, 1fr)', 
            gap: '40px 32px'
          }}>
            {menuSections.map((section, sectionIndex) => (
              <div key={sectionIndex} style={{ 
                minHeight: '180px'
              }}>
                {/* 分类标题 */}
                <div style={{ 
                  marginBottom: '16px'
                }}>
                  <span style={{ 
                    fontSize: '14px', 
                    fontWeight: 600, 
                    color: '#1890ff' 
                  }}>
                    {section.title}
                  </span>
                </div>

                {/* 分类内容 */}
                <div>
                  {section.items.map((item, itemIndex) => (
                    <div key={itemIndex} style={{ marginBottom: '12px' }}>
                      <div style={{ 
                        fontSize: '12px', 
                        fontWeight: 600, 
                        color: '#262626',
                        marginBottom: '6px'
                      }}>
                        {item.title}
                      </div>
                      {item.subItems.map((subItem, subIndex) => (
                        <div 
                          key={subIndex}
                          style={{ 
                            fontSize: '11px', 
                            color: '#8c8c8c',
                            cursor: 'pointer',
                            padding: '2px 0',
                            transition: 'color 0.2s',
                            lineHeight: '1.3'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.color = '#1890ff';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.color = '#8c8c8c';
                          }}
                          onClick={() => {
                            // 根据菜单项导航到对应页面
                            if (subItem === '资源管理') {
                              handleMenuItemClick('/app/containers');
                            } else if (subItem === '运维中心') {
                              handleMenuItemClick('/app/sites');
                            } else if (subItem === '分布式消息服务') {
                              handleMenuItemClick('/app/containers');
                            } else if (subItem === '监控中心') {
                              handleMenuItemClick('/app/certificates');
                            } else {
                              handleMenuItemClick('/app/dashboard');
                            }
                          }}
                        >
                          {subItem}
                        </div>
                      ))}
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      </Drawer>
    </>
  );
};

export default TopNavigation; 